<meta charset="utf-8"/>
<div class="row">
  <div class="col-xs-12">
    <div class="row">
      <div class="col-xs-12" style="padding-right:6px"><!--控制有水平滚动条的内边距-->
        <div class="col-xs-12">
          <div class="col-xs-3 div_scrollbar_role" style="margin-left:-9px;margin-top:4px;"><!--水平滚动条-->
            <div class="col-xs-12">
              <ul id="treeLevel" class="ztree" style="padding:0px;"></ul>
            </div>
          </div>
          <div class="col-xs-9">
            <div class="col-xs-12" style="margin-top:4px">
              <table class="no-border" style="display:inline;height:42px;">
                <tr>
                  <td permission='proxy_btn_ListData' class="hidden-480" style="padding:0px 6px;display:none">
                    参考项目 sso-frontend/src/main/resources/static/authManger.html
                  </td>
                  <td permission='proxy_btn_ListData' style="display:none">
                    <div class="input-group">
                      <input title="登录手机号码" type="text" class="form-control search-query hidden-480" id="key_username" placeholder="登录账号|手机号码" style="width:140px"/>
                      <span class="input-group-btn"><button type="button" class="btn btn-inverse btn-white" id="btnSearch"><span class="ace-icon fa fa-search bigger-110"></span>查询</button></span>
                    </div>
                  </td>
                  <td permission='proxy_btn_ListData' style="display:none">
                    <div class="input-group">
                      <span class="input-group-btn"><button type="button" class="btn btn-inverse btn-white" id="btnReset"><span class="ace-icon fa fa-undo bigger-110"></span>重置</button></span>
                    </div>
                  </td>
                </tr>
              </table>
              <div class="col-xs-12">
                <div style="width:100%;height:100%;">
                  <div style="min-height:824px;position:relative;">
                    <div style="position:absolute;left:0;top:0;right:-17px;bottom:0;overflow-x:auto;overflow-y:auto;" class="div_scrollbar_role">
                      <div style="min-width:1024px">
                        <table class="table table-striped table-bordered table-hover" id="tableAppUser">
                          <tbody>
                          <tr>
                            <td style="text-align:center;height:37px">正在加载……</td>
                          </tr>
                          </tbody>
                        </table>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
<div style="display:none" id="div_tree_level_wizard">
  <ul id="wizard_treeLevel" class="ztree" style="padding:0px;"></ul>
</div>
<div id="div_sys_user_edit" style="display:none;padding-top:1px;">
  <form class="form-horizontal" id="form_sys_user_edit" role="form">
    <label class="col-sm-3 control-label no-padding-right"><div class="hr-4">手机号码</div></label>
    <div class="col-sm-7">
      <div class="hr-4"></div>
      <input type="text" id="user_name" placeholder="手机号码" readonly class="form-control" maxlength="20" title="登录的手机号码" oninput="value=value.replace(/[^\d]/g,'')"/>
    </div>
    <label class="col-sm-3 control-label no-padding-right"><div class="hr-4">所属区域</div></label>
    <div class="col-sm-7">
      <div class="hr-4"></div>
      <span class="input-icon input-icon-right col-sm-12" style="padding:0;" title="选择所属区域">
        <input type="text" id="wizard_areaName" readonly placeholder="选择用户所属区域" class="form-control selectArea" style="cursor:pointer"/>
        <i class="ace-icon fa fa-hand-pointer-o green selectArea" style="margin-top:2px;cursor:pointer"></i>
      </span>
      <input id="area_id" type="hidden"/>
    </div>
    <label class="col-sm-3 control-label no-padding-right"><div class="hr-4">组织部门</div></label>
    <div class="col-sm-7">
      <div class="hr-4"></div>
      <div class="input-group">
        <span class="input-group-btn">
          <button data-toggle="dropdown" class="btn btn-primary btn-white dropdown-toggle col-sm-12" style="margin-left:0px;">
            <span id="wizard_dropdownLabelDept">选择组织部门</span>
            <i class="ace-icon fa fa-angle-down"></i>
          </button>
          <ul class="dropdown-menu col-sm-12" id="ulDropdownOptsDept_wizard"></ul>
          <input id="dept_id" type="hidden"/>
        </span>
      </div>
    </div>
    <label class="col-sm-3 control-label no-padding-right"><div class="hr-4">启停状态</div></label>
    <div class="col-sm-7">
      <div class="hr-4"></div>
      <div class="input-group">
        <span class="input-group-btn">
          <button data-toggle="dropdown" class="btn btn-primary btn-white dropdown-toggle col-sm-12" style="margin-left:0px;">
            <span id="dropdownLabelenabled">选择状态</span>
            <i class="ace-icon fa fa-angle-down"></i>
          </button>
          <ul class="dropdown-menu col-sm-12">
            <li>
              <a id="enabled_" href="javascript:winFn.dropdown('#enabled','','#dropdownLabelenabled','选择状态');">选择状态</a>
            </li>
            <li>
              <a id="enabled0" href="javascript:winFn.dropdown('#enabled',0,'#dropdownLabelenabled','启用');">启用</a>
            </li>
            <li>
              <a id="enabled1" href="javascript:winFn.dropdown('#enabled',1,'#dropdownLabelenabled','禁用');">禁用</a>
            </li>
          </ul>
          <input id="enabled" type="hidden"/>
        </span>
      </div>
    </div>
    <label class="col-sm-3 control-label no-padding-right"><div class="hr-4">用户姓名</div></label>
    <div class="col-sm-7">
      <div class="hr-4"></div>
      <input type="text" id="real_name" placeholder="用户姓名" class="form-control" maxlength="20"/>
    </div>
    <label class="col-sm-3 control-label no-padding-right"><div class="hr-4">身份证号</div></label>
    <div class="col-sm-7">
      <div class="hr-4"></div>
      <input type="text" id="user_card" placeholder="用户身份证号" class="form-control" maxlength="20" oninput="value=value.replace(/[^\d-xX]/g,'')"/>
    </div>
    <label class="col-sm-3 control-label no-padding-right"><div class="hr-4">电子邮箱</div></label>
    <div class="col-sm-7" style="padding-bottom:4px">
      <div class="hr-4"></div>
      <input type="text" id="email" placeholder="电子邮箱地址" class="form-control" maxlength="64"/>
    </div>
  </form>
</div>
<input id="key_dept_id" type="hidden"/><!--部门id-->
<input type="hidden" id="areaId_kid"/><!--区域id-->
<input type="hidden" id="wizard_new_areaId"/><!--用于获取下一级的树形数据-->
<script type="text/javascript">
  var urlRoute_wizard = '/auth/';//此url免登录,供auth.html原搬过来
  var urlGetAreaDept_wizard = urlRoute_wizard + 'getUserAreaDept';/*获取区域部门*/
  var wizard_treeLevel = null;
  //推荐使用
  var wizard_settingDept = areaDept.initAreaDom({
    url : '/auth/getAreaTree',//新增或编辑时用
    dataFilter : function(data){},
    callback : {//todo 此处是对象,不是方法!!!
      beforeClick : function(){},
      onClick : function(event,treeId,node){
        $('#wizard_new_areaId').val(node.area_id);//用于后端查询下一级的区域
        $('#area_id').val(node.kid);//用于保存到后端
        $('#wizard_areaName').val(node.name);
      }
    },
    areaClick : function(){
      $('.selectArea').on('click',function(){
        layerFn.addOrEditCallBack('选择所属区域','#div_tree_level_wizard',['500px','450px'],function(layero){
          var areaId = $('#wizard_new_areaId').val();
          if(areaId == undefined || areaId == ''){
            layerFn.alert('请选择行政区域',AppKey.code.code199);
            return;
          }
          //编辑时确定后置空'选择组织部门'
          $('#wizard_dropdownLabelDept').text('选择组织部门');
          $('#dept_id').val('');
          layerFn.closeIndex(layero);
          thisPage.initSelectEdit(areaId);
        },function(){
          thisPage.initEditTree();
        });
      });
    }
  });
  
  var treeLevel = null;
  var settingDept = areaDept.initAreaDom({
    url : '/anthManager/getAreaTree',
    dataFilter : function(data){},
    param : ['area_id','target'],
    callback : {
      onClick : function(event,treeId,node){
        if(node.target == 2){//仅通过部门id去查询
          $('#key_dept_id').val(node.newId);
          $('#areaId_kid').val('');
        }else{//仅通过新的区域id查询
          $('#area_id').val(node.newId);//用于保存到后端,免去选择区域
          $('#key_dept_id').val('');
          $('#areaId_kid').val(node.newId);//用于查询bigint类型
          $('#wizard_areaName').val(node.name);
          thisPage.initSelectEdit(node.area_id);
        }
        thisPage.getUserListData();
      }
    }
  });
  var thisJqueryUser = null;
  var thisTableUser = null;//数据表格搜索或刷新
  $(function($){
    var urlRoute = '/anthManager/';
    var getListData = urlRoute + 'ListData';/*获取发改部门*/
    var urlEditEnabled = urlRoute + 'editEnabled';/*启禁用*/
    var urlQueryById = urlRoute + 'queryById';/*查询详情*/
    var cancelAuth = urlRoute + 'editCancelAuth';/*取消认证*/
    var editAuthUser = urlRoute + 'edit';/*行内编辑*/
    var addAuthUser = urlRoute + 'add';/*新增（添加）*/
    var getExport = urlRoute + 'getDataExport';/*获取导出的数据*/
    thisPage = {
      init : function(){
        this.initDom();
        this.btnEvent();
      },
      initDom : function(){
        this.initTree();
        thisPage.getUserListData();//填充数据表格
      },
      initScrollbarRole : function(dom){
        $(dom).mCustomScrollbar({
          axis:"x",
          scrollbarPosition:"outside",
          advanced:{autoExpandHorizontalScroll:true}
        });
      },
      initTree : function(){
        authHandler('proxy_btn_areaTree', function(){
          thisPage.ztreeGetError('正在加载……');
          treeLevel = $.fn.zTree.init($("#treeLevel"), settingDept);
        }, function(){
          thisPage.ztreeGetError('暂无访问权限');
        });
      },
      //用于编辑或添加的树形数据
      initEditTree : function(){
        wizard_treeLevel = $.fn.zTree.init($("#wizard_treeLevel"),wizard_settingDept);
      },
      ztreeGetError : function(msg){
        msg = (msg == null || msg == '') ? '获取数据失败' : msg;
        $("#treeLevel").html("<li style='margin-top:2px;'><span>"+msg+"</span></li>");
      },
      btnEvent : function(){
        $('#btnSearch').on('click',function(){
          thisPage.initTableData();
        });
        $('#btnAdd').on('click',function(){
          $('#user_name').removeAttr("readonly");
          thisPage.openDialog('新增用户信息',null,null);
        });
        $('#btnReset').on('click',function(){
          $('#areaId_kid').val('');
          $('#key_username').val('');
          $('#key_dept_id').val('');
        });
        //导出
        $('#btnExport').on('click', function(){
          var params = {};
          params["kid"] = winFn.getDomValue('#areaId_kid');
          params["user_name"] = winFn.getDomValue('#key_username');
          params["dept_id"] = winFn.getDomValue('#key_dept_id');
          var urlParams = '';
          for(k in params){
            var v = params[k];
            if(v != null){
              if(urlParams != ''){
                urlParams += '&' + k + '=' + v;
              }else{
                urlParams += k + '=' + v;
              }
            }
          }
          var zIndexLayer = layerFn.confirm('确定要导出当前的全部数据吗？处理完成将会自动下载，请等待……',function(){
            winFn.getPageHashToken(getExport+'?'+urlParams);
          });
          $('#layui-layer' + zIndexLayer + ' a.layui-layer-btn0').text('导出');
        });
      },
      //用于编辑或添加的组织部门
      initSelectEdit : function(kid){
        layerFn.queryHintNoIntercept(urlGetAreaDept_wizard,{kid:kid},function(data){
          if(data.code == AppKey.code.code200){
            winFn.initDropdown(data.data,'#ulDropdownOptsDept_wizard','#dept_id','#wizard_dropdownLabelDept','选择组织部门');
          }else{
            winFn.initDropdown([],'#ulDropdownOptsDept_wizard','#dept_id','#wizard_dropdownLabelDept','选择组织部门');
          }
        });
      },
      //填充数据表格
      getUserListData : function(){
        authHandler('proxy_btn_ListData', function(){
          thisPage.initTableData();
        },function(){});
      },
      //获取发改委数据并填充table
      initTableData : function(){
        thisTableUser = pageDataTable.initDataTable({
          tableDom : '#tableAppUser',
          sAjaxSource : getListData,
          fnServerParams : function(params){
            params.push(
              {"name":"kid","value":$('#areaId_kid').val()},
              {"name":"user_name","value":$('#key_username').val()},
              {"name":"dept_id","value":$('#key_dept_id').val()}
            );
          },
          aoColumns : [
            {
              mData : "user_name",
              bSortable : false,
              sTitle : "登录账号",
              render : function(value){
                if(value){
                  return value;
                }else{
                  return "";
                }
              }
            },
            {
              mData : "real_name",
              bSortable : false,
              sTitle : "姓名",
              render : function(value){
                if(value){
                  return value;
                }else{
                  return "";
                }
              }
            },
            {
              mData : "sex",
              bSortable : false,
              sTitle : "性别",
              render : function(value){
                if(value){
                  switch (value){
                    case 1:
                      return '男生';
                    case 2:
                      return '女生';
                    default:
                      return '';
                  }
                }else{
                  return "";
                }
              }
            },
            {
              mData : "deleted",
              bSortable : false,
              sTitle : "账号状态",
              sWidth: "6%",
              render : function(value, type, row){
                if(row.deleted == 1){
                  return "已删除";
                }else{
                  return row.enabled == 1 ? '禁用' : '正常';
                }
              }
            },
            {
              mData : "times",
              bSortable : false,
              sTitle : "登录次数",
              sWidth: "6%",
              render : function(value, type, row){
                return value;
              }
            },
            {
              mData : "logintime",
              bSortable : false,
              sTitle : "最后登录时间",
              sWidth: "10%",
              render : function(value, type, row){
                return value;
              }
            },
            {
              mData : "areaName",
              bSortable : false,
              sTitle : "所属区域",
              render : function(value){
                if(value){
                  return value;
                }else{
                  return "";
                }
              }
            },
            {
              mData : "org_name",
              bSortable : false,
              sTitle : "所属部门机构",
              render : function(value){
                if(value){
                  return value;
                }else{
                  return "";
                }
              }
            },
            {
              mData : "appNames",
              bSortable : false,
              sTitle : "访问应用",
              sWidth: "8%",
              render : function(value){
                if(value){
                  return '<a href="javascript:thisPage.previewDetails(\''+value+'\');">查看应用</a>';
                }else{
                  return '';
                }
              }
            },
            {
              mData : "_kid_",
              sWidth: "75px",
              sTitle : "<label style='color:#000;margin-left:6px;' title='单行操作'>操作选项</label>",
              bSortable : false,
              //visible : getOptsVisible('article_row')
            }
          ],
          columnDefs : [
            {
              targets : -1,
              render : function(value, type, row, meta){
                return "<a href='javascript:thisPage.rowEdit(" + meta.row + ");' style='margin-left:4px;display:none' permission='proxy_row_edit'>编辑</a>"+
                "<a href='javascript:thisPage.cancelAuth(\""+meta.row+"\");' style='color:#1ba2d7;margin-left:6px;display:none' permission='proxy_row_cancelAuth' title='取消认证'>删除</a>";
              }
            },
            {
              visible : false,//列的隐藏显示
              targets : []//指定列
            }
          ]
        });
        thisJqueryUser = $('#tableAppUser').dataTable();
      },
      //搜索
      searchUser : function(){
        thisTableUser.draw();
      },
      cancelAuth : function(index){
        var row = thisJqueryUser.fnGetData(index);
        authHandler('proxy_row_cancelAuth', function(){
          layerFn.confirm('你确定要对['+row.user_name+']进行<span style="color:#16b8f3;">删除</span>操作吗?',function(){
            layerFn.submit(cancelAuth,{kid : row.kid},function(data){
              thisPage.complete(data,null, true);
              thisPage.searchUser();
            });
          });
        },function(){
          layerFn.alert('没有访问权限',AppKey.code.code199);
        });
      },
      previewDetails : function(value){
        var array = value.split(',');
        var html = '';
        for(var o=0;o<array.length;o++){
          if(html != ''){
            html += '<br/>' + array[o];
          }else{
            html += array[o];
          }
        }
        layerFn.viewValue(html,'310px');
      },
      resetForm : function(){
        $('#user_name').val('');
        $('#wizard_dropdownLabelDept').text('选择组织部门');
        $('#dept_id').val('');
        winFn.addDropdown('#dropdownLabelenabled','选择状态');
        $('#enabled').val('');
        $('#real_name').val('');
        $('#user_card').val('');
        $('#email').val('');
      },
      rowEdit : function(index){
        var row = thisJqueryUser.fnGetData(index);
        layerFn.queryByIdHint(urlQueryById, row.kid, function(data){
          $('#user_name').attr("readonly",true);
          thisPage.openDialog('编辑用户信息',row.kid, data);
        });
      },
      openDialog: function(title, kid, map){
        authHandler('proxy_row_edit',function(){
          layerFn.addOrEdit(title,'#div_sys_user_edit', ['500px','356px'], function(layerIndex, layero){
            if(verifyFn.inputCheck('#user_name','手机号码不能为空')) return;
            if(verifyFn.inputCheck('#area_id','请选择所属区域')) return;
            if(verifyFn.inputCheck('#dept_id','请选择组织部门')) return;
            if(verifyFn.inputCheck('#enabled','请选择账号启停状态')) return;
            if(verifyFn.inputCheck('#real_name','用户姓名不能为空')) return;
            if(verifyFn.inputCheck('#user_card','身份证号不能为空')) return;
            if(verifyFn.inputCheck('#email','电子邮箱不能为空')) return;
            var user_name = winFn.getDomValue('#user_name');
            //验证手机号码
            var reg_phone = /^1[0-9]{10}$/;
            var flag_phone = reg_phone.test(user_name);
            if(!flag_phone){
              layerFn.handleTop('请输入正确的手机号码',AppKey.code.code199);
              return;
            }
            var identityCode = winFn.getDomValue('#user_card');
            //验证身份证号码
            var reg_identity = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
            var flag_identity = reg_identity.test(identityCode);
            if(!flag_identity){
              layerFn.handleTop('请输入正确的身份证号码',AppKey.code.code199);
              return;
            }
            var email = winFn.getDomValue('#email');
            //验证邮箱
            var reg_email = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/;
            var flag_email = reg_email.test(email);
            if(!flag_email){
              layerFn.handleTop('请输入正确的邮箱地址',AppKey.code.code199);
              return;
            }
            var params = {
              user_name : winFn.getDomValue('#user_name'),
              password : (kid == null) ? identityCode.substring(identityCode.length - 6) : null,
              real_name : winFn.getDomValue('#real_name'),
              user_card : winFn.getDomValue('#user_card').toUpperCase(),
              enabled : winFn.getDomValue('#enabled'),
              email : winFn.getDomValue('#email'),
              area_id : winFn.getDomValue('#area_id'),
              dept_id : winFn.getDomValue('#dept_id'),
              kid : kid
            };
            layerFn.submit((kid == null) ? addAuthUser : editAuthUser, params, function(data){
              thisPage.complete(data, layerIndex, true);
            });
          });
          thisPage.resetForm();//清空
          if(map != null){
            $.each(map.data, function(k, v){
              try{
                $('#' + k).val(v);
                if(k == 'enabled'){
                  winFn.editDropdown('#dropdownLabelenabled','enabled' + v);
                }
                if(k == 'areaName'){
                  $('#wizard_areaName').val(v);
                }
                if(k == 'org_name'){
                  $('#wizard_dropdownLabelDept').text(v);
                }
              }catch(e){}
            });
          }
        },function(){
          layerFn.alert('暂无操作权限',AppKey.code.code199);
        });
      },
      rowEnabled : function(index){
        authHandler('proxy_row_enabled', function(){
          var row = thisJqueryUser.fnGetData(index);
          var status = row.enabled;
          var deleted = row.deleted;
          if(deleted == 1){
            layerFn.alert('账号已删除无需操作',AppKey.code.code199);
            return;
          }
          var msg = status == 1 ? "启用" : "禁用";
          var target = status == 1 ? 0 : 1;
          layerFn.confirm('你确定要['+row.user_name+']进行<span style="color:#16b8f3;">'+msg+'</span>操作吗?',function(){
            var params = {
              kid : row.kid,
              target : target
            };
            layerFn.submit(urlEditEnabled,params,function(data){
              thisPage.complete(data,layerIndex,true);
            });
          });
        },function(){
          layerFn.alert('没有访问权限',AppKey.code.code199);
        });
      },
      complete: function(data, index, search){
        try{
          if(index){
            layerFn.closeIndex(index);
          }
          if(search){
            thisPage.searchUser();
          }
          if(data){
            layerFn.handleResult(data.msg, data.code);
          }
        }catch(e){}
      }
    }
    thisPage.init();
    $('script').remove();
  });
</script>